package cn.maihe.elg.operation.service.business;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import cn.maihe.elg.operation.model.vo.business.ListProjectInfoVO;
import cn.maihe.elg.operation.repository.entity.ProjectInfoDO;
import cn.maihe.elg.operation.repository.entity.ProjectInfoDOCondition;
import cn.maihe.elg.operation.repository.mapper.ProjectInfoMapper;
import cn.maihe.elg.operation.service.BaseDaoService;
import cn.maihe.elg.operation.utils.DateUtil;
import cn.maihe.elg.operation.utils.IdGenerate;
import cn.maihe.framework.starter.base.sql.PageBo;
import cn.maihe.framework.starter.mybatis.dao.MybatisDaoImpl;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.Map;

/**
 * @Description 投标项目信息服务
 * @Author WJH
 * @Date 2021/03/25
 */
@Service
public class ProjectInfoService extends BaseDaoService<ProjectInfoDO> {

    public PageBo<ListProjectInfoVO> selectPageBySql(int pageNo, int pageSize,ListProjectInfoVO vo) {
        Map<String, Object> paramsMap = toMapAndAddParams(vo);
        if (vo.getBidOpenTimeRange() != null && vo.getBidOpenTimeRange().length == 2) {
            String[] rangeAy = vo.getBidOpenTimeRange();
            if (StringUtils.isNoneBlank(rangeAy[0], rangeAy[1])) {
                paramsMap.put("startBidOpenTime", DateUtil.parseDate(rangeAy[0] + " 00:00:00", "yyyy-MM-dd HH:mm:ss"));
                paramsMap.put("endBidOpenTime", DateUtil.parseDate(rangeAy[1] + " 23:59:59", "yyyy-MM-dd HH:mm:ss"));
            }
        }
        if(StringUtils.isNotBlank(vo.getMinBidBond())){
            paramsMap.put("minBidBondFen", NumberUtil.mul(vo.getMinBidBond(),"100").longValue());
        }
        if(StringUtils.isNotBlank(vo.getMaxBidBond())){
            paramsMap.put("maxBidBondFen", NumberUtil.mul(vo.getMaxBidBond(),"100").longValue());
        }
        String sortColumn = vo.getSortColumn();
        if (StringUtils.isNotBlank(sortColumn)) {
            String[] sc = sortColumn.split("_");
            if(sc.length==2 && !"normal".equalsIgnoreCase(sc[1].trim())){
                String columnName = StrUtil.toUnderlineCase(sc[0]);
                String order = sc[1];
                paramsMap.put("orderByColumn", "t.".concat(columnName).concat(" ").concat(order));
            }
        }
        return this.selectPageBySql("selectProjectList", "selectProjectCount", paramsMap, pageNo, pageSize);
    }

    public boolean existsSectionCode(String sectionCode, Long centerId, Long orgId, Long excludeSelfProjectId) {
        Assert.notNull(sectionCode, "标段编码不能为空");
        Assert.notNull(centerId, "centerId不能为空");
        Assert.notNull(orgId, "orgId不能为空");

        ProjectInfoDOCondition condition = ProjectInfoDOCondition.builder().andSectionCodeEq(sectionCode)
                .andCenterIdEq(centerId).andOrgIdEq(orgId);
        if (excludeSelfProjectId != null) {
            condition.andIdNe(excludeSelfProjectId);
        }
        return this.exists(condition.build());
    }


    public ProjectInfoDO getBySectionCode(String sectionCode, String sectionName, Long centerId, Long orgId) {
        Assert.notNull(sectionCode, "标段编码不能为空");
        Assert.notNull(centerId, "centerId不能为空");
        Assert.notNull(orgId, "orgId不能为空");

        ProjectInfoDOCondition condition = ProjectInfoDOCondition.builder().andSectionCodeEq(sectionCode)
                .andCenterIdEq(centerId).andOrgIdEq(orgId);

        if(StringUtils.isNotBlank(sectionName)){
            condition.andSectionNameEq(sectionName);
        }
        return selectOne(condition.build());
    }

    public boolean existsProjectLinkedAcceptOrder(Long id) {
        Map<String, Object> paramsMap = Maps.newHashMap();
        paramsMap.put("projectId", id);
        return MybatisDaoImpl.of(ProjectInfoMapper.class).selectCountBySql("existsProjectLinkedAcceptOrder", paramsMap) > 0;
    }

    public ListProjectInfoVO getProjectInfoDetailById(Long id) {
        Map<String, Object> paramsMap = Maps.newHashMap();
        paramsMap.put("id", id);
        return MybatisDaoImpl.of(ProjectInfoMapper.class).selectOneBySql("getProjectInfoDetailById", paramsMap);
    }

    public ProjectInfoDO saveOrUpdateProjectInfo(ProjectInfoDO cur) {
        Assert.notNull(cur, "入参ProjectInfoDO不能为空");
        String sectionCode = cur.getSectionCode();
        Long centerId = cur.getCenterId();
        Long orgId = cur.getOrgId();

        Assert.hasText(sectionCode, "参数标段编码不能为空");
        Assert.notNull(centerId, "参数中心主键id不能为空");
        Assert.notNull(orgId, "参数机构主键id不能为空");

        ProjectInfoDO dbDO = this.getBySectionCode(sectionCode, cur.getSectionName(), centerId, orgId);
        if (dbDO != null) {
            cur.setId(dbDO.getId());
            cur.setGmtModified(Date.from(Instant.now()));
            this.updateById(cur);
        } else {
            cur.setId(cur.getId() != null ? cur.getId() : IdGenerate.getId());
            cur.setGmtCreate(Date.from(Instant.now()));
            cur.setGmtModified(cur.getGmtCreate());
            this.insert(cur);
        }
        return this.selectById(cur.getId());
    }
    public Date getServiceEndDate(ProjectInfoDO projectInfo){
        Date serviceEndDate = Date.from(projectInfo.getBidOpenTime().toInstant()
                .plus((projectInfo.getValidPeriod() == null ? 0 : projectInfo.getValidPeriod()) + 28, ChronoUnit.DAYS));
        return serviceEndDate;
    }
}
